<template>
	<!-- 下拉选择器，用于选择配方 -->
	<el-popover v-model="isShow" width="300" :disabled="!hasRecipes" trigger="click" class="recipe_picker el-select">
		<!-- 配方列表 -->
		<div class="list_container">
			<div v-for="(recipe, index) in recipeList" :key="index" @click="handleSelect(recipe)" class="recipe">
				<simple-recipe-show :recipe="recipe" />
			</div>
		</div>

		<!-- 选择器的引用元素 -->
		<div slot="reference" class="recipe_show el-input">
			<template v-if="loaded">
				<template v-if="hasRecipes">
					<simple-recipe-show :recipe="recipe" />
					<span class="el-input__suffix">
						<span class="el-input__suffix-inner">
							<i
								:class="'el-select__caret el-input__icon el-icon-arrow-up' + (isShow ? ' is-reverse':'')" />
						</span>
					</span>
				</template>
				<div v-else class="no_recipe_show">
					该物品暂无配方
				</div>
			</template>
		</div>
	</el-popover>
</template>

<script>
	import Vue from 'vue';
	import SimpleRecipeShow from '@/components/SimpleRecipeShow.vue';

	export default {
		name: 'RecipePicker',
		components: {
			SimpleRecipeShow
		},
		props: {
			recipeId: {
				type: Number,
				required: true
			},
			itemId: {
				type: Number,
				required: true
			},
			index: {
				type: Number,
				required: true
			}
		},
		emits: ['update'],
		data() {
			return {
				recipeList: [],
				isShow: false,
				loaded: false,
			};
		},
		computed: {
			recipe() {
				return this.recipeList.find(r => r.id === this.recipeId) || {};
			},
			hasRecipes() {
				return this.recipeList.length > 0;
			}
		},
		methods: {
			handleSelect(recipe) {
				this.$emit("update", this.itemId, recipe.id);
				this.isShow = false;
			},
			handleShow() {
				if (!this.loaded) {
					this.$api.get("/recipe/cal/list", {
						item: this.itemId
					}).then((res) => {
						if (res.code === 0) {
							this.recipeList = res.data.list;
							this.loaded = true;
						}
					});
				}
			}
		},
		mounted() {
			this.handleShow();
		}
	};
</script>

<style lang="less" scoped>
	@import url("/src/assets/less/variables.less");

	.list_container {

		.recipe {
			margin: 10px;
		}
	}

	.recipe_picker {
		width: 100%;
		// height: 100px;


		.recipe_show {
			// height: 100px;
		}

		.no_recipe_show {
			width: 100%;
			height: 100px;
			text-align: center;
			line-height: 80px;
			font-size: 20px;
			background: @color-disabled;
			color: @color-subtext;
			border: 1px dashed @color-border;
		}

		.el-input__suffix {
			color: @color-subtext;
		}
	}
</style>